//
//  NewestTopView.m
//  livingDesign
//
//  Created by dlios on 15-1-29.
//  Copyright (c) 2015年 怡居. All rights reserved.
//

#import "NewestTopView.h"

@implementation NewestTopView
- (void)dealloc
{
    [_image release];
    [_imageView release];
    [_scrollerView release];
    [_pageControl release];
    [super dealloc];
    
}
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        // top的ScrollerView
        self.scrollerView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width , self.frame.size.height)];
        [self addSubview:self.scrollerView];
        self.scrollerView.backgroundColor = [UIColor yellowColor];
        self.scrollerView.contentSize = CGSizeMake(self.frame.size.width * 3, 0);
        self.scrollerView.pagingEnabled = YES;
        self.scrollerView.delegate = self;
        [self.scrollerView release];
        
        // ScrollerView的图片
        for (NSInteger i = 0 ; i < 3; i++) {
            self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0 + self.frame.size.width * i, 0, self.frame.size.width, self.frame.size.height)];
            [self.scrollerView addSubview:self.imageView];
            self.imageView.backgroundColor = [UIColor redColor];
            NSString *imageStr = [NSString stringWithFormat:@"yiju_%ld.jpg", i+1];
            self.image = [UIImage imageNamed:imageStr];
            self.imageView.image = self.image;
            [self.imageView release];
        }
        
        // pageControl
        self.pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(self.frame.size.width / 3 + 50, self.frame.size.height - 20, 30, 10)];
        [self addSubview:self.pageControl];
        self.pageControl.numberOfPages = 3;
        [self.pageControl addTarget:self action:@selector(pageAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.pageControl release];
        
        // 设置计时器
        [NSTimer scheduledTimerWithTimeInterval:5.0f target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
        self.num = 0;
    }
    return self;
}
// 计时器方法
- (void)timerAction:(NSTimer *)timer
{
    if (self.num != 2) {
        self.scrollerView.contentOffset = CGPointMake(self.num * self.frame.size.width, 0);
        self.num++;
    }
    else
    {
        self.scrollerView.contentOffset = CGPointMake(2 * self.frame.size.width, 0);
        self.num = 0;
    }
    
}

// pageControl方法
- (void)pageAction:(UIPageControl *)page
{
    
    self.scrollerView.contentOffset = CGPointMake(page.currentPage * self.frame.size.width, 0);
}
// scrollerView的协议方法
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    self.pageControl.currentPage = self.scrollerView.contentOffset.x / self.frame.size.width;
}

@end
